<?php

namespace Addons\OaSystem\Controller;

use Think\ApiBaseController;

class ApiNoticeController extends ApiBaseController
{
    var $openid;
    var $appid;
    var $cur_emp_id;
    var $initial_check_pass;

    public function __construct()
    {
        $this->initial_check_pass = false;
        parent::__construct();
        $this->openid = get_openid();
        $this->appid = get_app_info()['appid'];
        if ($this->openid == -1) {
            $return['errcode'] = '40003';
            echo api_return($return['errcode'], null, error_msg($return));
            exit;
        }
        $map['userid'] = $this->mid;
        $userEmp = M('OaUserEmployee')->where($map)->find();
        if (empty($userEmp)) {
            $return['errcode'] = '50001';
            echo api_return($return['errcode'], null, error_msg($return, "找不到对应的员工号"));
            exit;
        }
        $this->cur_emp_id = $userEmp['emp_id'];
        $this->initial_check_pass = true;
    }

    public function GetFirstFiveNoticeList() {
        if(!$this->initial_check_pass) {
            return;
        }
        $map['type'] = array('in',array(0,1,2));
        $map['appid'] = $this->appid;
        $map['emp_id'] = $this->cur_emp_id;
        $notices = D('OaEmpMsgNoticeView')->where($map)->order('time desc')->page(1,5)->select();
        $map['is_read'] = array('neq',1);
        $count = D('OaEmpMsg')->where($map)->count();
        $s_map['receiver'] = $this->cur_emp_id;
        $s_map['is_read'] = array('neq',1);
        $s_map['pid'] = 0;
        $count = $count + M('OaNoticeTaskReply')->where($s_map)->count();
        $data['newcount'] = $count;
        $data['notices'] = array();
        for($i =$j= 0; $i < count($notices); $i++) {
            if ($notices[$i]['type'] == 2) {
                $tmpMap['noticeid'] = $notices[$i]['noticeid'];
                $tmpMap['receiver'] = $this->cur_emp_id;
                $tmpMap['pid'] = 0;
                $father_reply = M('OaNoticeTaskReply')->where($tmpMap)->find();
                $notices[$i]['is_read'] = $father_reply['is_read'];
                if (($this->cur_emp_id == $notices[$i]['creater']) || ($this->cur_emp_id == $notices[$i]['leader'])){
                    $notices[$i]['subtype'] = 0;
                    array_push($data['notices'],$notices[$i]);
                    $j++;
                }
                if ($j == 5) {
                    break;
                }
                $toUsers = json_decode($notices[$i]['to_users'],true);
                if (in_array($this->cur_emp_id,$toUsers)){
                    $notices[$i]['subtype'] = 1;
                    array_push($data['notices'],$notices[$i]);
                    $j++;
                }
                if ($j == 5) {
                    break;
                }
            } else if ($notices[$i]['type'] == 1) {
                $notices[$i]['replyState'] = 0;
                if ($notices[$i]['creater'] == $this->cur_emp_id) {
                    $notices[$i]['replyState'] = $this->getMyNoticeStatus($notices[$i]['noticeid']);
                }
                array_push($data['notices'],$notices[$i]);
                $j++;
                if ($j == 5) {
                    break;
                }
            } else {
                array_push($data['notices'],$notices[$i]);
                $j++;
                if ($j == 5) {
                    break;
                }
            }
        }
        echo api_return(0,$data);
    }

    private function getMyNoticeStatus ($noticeId) {
        // 0: default, 1:全部确认参加，2:部分确认参加，3:有人未确认，4:有人未读
        $map['noticeid'] = $noticeId;
        $notices = D('OaEmpMsgNoticeView')->where($map)->select();
        $confirm = 1;
        foreach ($notices as $notice) {
            if($notice['creater'] == $notice['emp_id']) {
                continue;
            }
            if ($notice['is_read'] == 0) {
                $confirm =  4;
            }
            if($notice['reply'] == 0) {
                if ($confirm < 3){
                    $confirm = 3;
                }
            }
            if($notice['reply'] == 2) {
                if ($confirm < 2){
                    $confirm = 2;
                }
            }
        }

        return $confirm;
    }
    public function GetAllNoticeList() {
        if(!$this->initial_check_pass) {
            return;
        }
        if(empty(I('page'))) {
            $map['type'] = array('in',[0,1]);
            $map['appid'] = $this->appid;
            $map['emp_id'] = $this->cur_emp_id;
            $notices = D('OaEmpMsgNoticeView')->where($map)->order('time desc')->select();
            for($i = 0; $i < count($notices); $i++) {
                // 0: default, 1:全部确认参加，2:部分确认参加，3:有人未确认，4:有人未读
                $notices[$i]['replyState'] = 0;
                if ($notices[$i]['creater'] == $this->cur_emp_id) {
                    $notices[$i]['replyState'] = $this->getMyNoticeStatus($notices[$i]['noticeid']);
                }
            }
            echo api_return(0,$notices);
        } else {
            $p = I('page');
            $map['type'] = array('in',[0,1]);
            $map['appid'] = $this->appid;
            $map['emp_id'] = $this->cur_emp_id;
            $notices = D('OaEmpMsgNoticeView')->where($map)->order('time desc')->page($p,20)->select();
            for($i = 0; $i < count($notices); $i++) {
                // 0: default, 1:全部确认参加，2:部分确认参加，3:有人未确认，4:有人未读
                $notices[$i]['replyState'] = 0;
                if ($notices[$i]['creater'] == $this->cur_emp_id) {
                    $notices[$i]['replyState'] = $this->getMyNoticeStatus($notices[$i]['noticeid']);
                }
            }
            echo api_return(0,$notices);
        }
    }

    public function GetAllSuperviseList() {
        if(!$this->initial_check_pass) {
            return;
        }
        $data = array();
        $notices = array();
        if(empty(I('page'))) {
            $map['receiver'] = $this->cur_emp_id;
            $map['pid'] = 0;
            $notices = D('OaNoticeTaskReplyNoticeView')->where($map)->order('time desc')->select();
        } else {
            $p = I('page');
            $map['receiver'] = $this->cur_emp_id;
            $map['pid'] = 0;
            $notices = D('OaNoticeTaskReplyNoticeView')->where($map)->order('time desc')->page($p,20)->select();
        }
        for($i = 0; $i < count($notices); $i++){
            $rep_map['pid'] = $notices[$i]['id'];
            $rep_map['receiver'] = $this->cur_emp_id;
            $rep_map['is_read'] = array('neq',1);
            $notices[$i]['hasnew'] = M('OaNoticeTaskReply')->where($rep_map)->count();
            if (($this->cur_emp_id == $notices[$i]['creater']) || ($this->cur_emp_id == $notices[$i]['leader'])){
                $notices[$i]['subtype'] = 0;
                array_push($data,$notices[$i]);
            }
            $toUsers = json_decode($notices[$i]['to_users'],true);
            if (in_array($this->cur_emp_id,$toUsers)){
                $notices[$i]['subtype'] = 1;
                array_push($data,$notices[$i]);
            }
        }
        echo api_return(0,$data);
    }

    public function GetAllNoticeMsgByNoticeId () {
        if(!$this->initial_check_pass) {
            return;
        }
        if (empty(I('noticeid'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }

        $map['noticeid'] = I('noticeid');
        $notices = D('OaEmpMsgNoticeView')->where($map)->select();
        echo api_return(0,$notices);
    }

    public function SetMsgReadFlag () {
        if (empty(I('id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
        }
        $data = M('OaEmpMsg')->where(array('id'=>I('id')))->find();
        if(empty($data)){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return,'id is wrong'));
        }
        $data['is_read'] = 1;
        M('OaEmpMsg')->where(array('id'=>I('id')))->save($data);
        echo api_return(0,null);
    }

    public function ConformJoinMetting () {
        if (empty(I('id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        if (empty(I('status'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        $data = M('OaEmpMsg')->where(array('id'=>I('id')))->find();
        if(empty($data)){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return,'id is wrong'));
        }
        $data['reply'] = I('status');
        M('OaEmpMsg')->where(array('id'=>I('id')))->save($data);
        echo api_return(0,null);
    }

    public function UpdateStatusOfSupperviseReply() {
        $trasctor = I('transactor');
        $status = I('status');
        $map['noticeid'] = I('noticeid');
        $map['receiver'] = $trasctor;
        $map['pid'] = 0;
        $father_reply = M('OaNoticeTaskReply')->where($map)->find();
        if (empty($father_reply)) {
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        if ( ($status == 1) && ($father_reply['is_read'] > 1)){
            echo api_return(0,$father_reply);
            return;
        }
        if (($status == 3) and ($father_reply['is_read'] != 2)) {
            echo api_return(0,$father_reply);
            return;
        }
        $father_reply['is_read'] = $status;
        M('OaNoticeTaskReply')->save($father_reply);
        echo api_return(0,$father_reply);
    }

    public function SetReadFlagOfSupperviseRelpyBySender() {
        $map['noticeid'] = I('noticeid');
        $map['receiver'] = $this->cur_emp_id;
        $map['sender'] = I('sender');
        $map['is_read'] = array('neq',1);
        $replies = M('OaNoticeTaskReply')->where($map)->select();
        // var_dump($replies);
        foreach ($replies as $reply) {
            $reply['is_read'] = 1;
            M('OaNoticeTaskReply')->where(array('id'=>$reply['id']))->save($reply);
        }
        echo api_return(0,null);
    }

    public function SetReadFlagOfSupperviseReply() {
        $map['noticeid'] = I('noticeid');
        $map['receiver'] = $this->cur_emp_id;
        $map['pid'] = 0;
        $father_reply = M('OaNoticeTaskReply')->where($map)->find();
        if (empty($father_reply)) {
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        /*
        $father_reply['is_read'] = 1;
        $ret = M('OaNoticeTaskReply')->save($father_reply);
        if ($ret === false) {
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return,'save'));
            return;
        }
        */
        $map['pid'] = $father_reply['id'];
        $map['is_read'] = array('neq',1);
        $replies = M('OaNoticeTaskReply')->where($map)->select();

        foreach ($replies as $reply) {
            $reply['is_read'] = 1;
            M('OaNoticeTaskReply')->where(array('id'=>$reply['id']))->save($reply);
        }
        echo api_return(0,null);
    }

    public function GetAllSupperviseReplies() {
        $map['id'] = I('noticeid');
        $notice = M('OaNotice')->where($map)->find();
        $data = array();

        $subtype = empty(I('subtype'))?0:I('subtype');
        if((($notice['creater'] == $this->cur_emp_id) || ($notice['leader'] == $this->cur_emp_id))
            and ($subtype == 0)){
            $rp_map['noticeid'] = $notice['id'];
            $rp_map['pid'] = 0;
            $rp_map['receiver'] = array('in',json_decode($notice['to_users'],true));
            $father_replies = D('OaNoticeTaskReplySenderView')->where($rp_map)->select();
            foreach ($father_replies as $reply){
                $tmp['status'] = $reply['is_read'];
                $tmp['type'] = '0'; // 0: 督办发起管理者
                $tmp['noticeid'] = $notice['id'];
                $tmp['name'] = $reply['receivername'];
                $tmp['pid'] = $reply['id'];
                $tmp['creater'] = $reply['sender'];
                $tmp['receiver'] = $reply['receiver'];
                $tmp['replies'] = D('OaNoticeTaskReplySenderView')->where(array('pid'=>$reply['id']))->select();
                array_push($data,$tmp);
            }
        } else {
            $rp_map['noticeid'] = $notice['id'];
            $rp_map['receiver'] = $this->cur_emp_id;
            $rp_map['pid'] = 0;
            $father_reply = D('OaNoticeTaskReplySenderView')->where($rp_map)->find();
            $tmp['status'] = $father_reply['is_read'];
            $tmp['type'] = 1; // 1: 督办任务接收者
            $tmp['noticeid'] = $notice['id'];
            $tmp['name'] = $father_reply['sendername'];
            $tmp['pid'] = $father_reply['id'];
            $tmp['creater'] = $father_reply['sender'];
            $tmp['receiver'] = $father_reply['receiver'];
            $tmp['replies'] = D('OaNoticeTaskReplySenderView')->where(array('pid'=>$father_reply['id']))->select();
            array_push($data,$tmp);
        }
        echo api_return(0,$data);
    }

    private function updateNoticeState($noticeId) {
        // 1:已发送， 2:新消息, 3: 已处理 4:已完成
        $notice = M('OaNotice')->where(array('id'=>$noticeId))->find();
        $map['noticeid'] = $noticeId;
        $map['pid'] = 0;
        $father_replies = M('OaNoticeTaskReply')->where($map)->select();

        $sendFlag = 0;
        $taskManage = 0;
        $taskDone = 0;
        $status = 1;
        foreach ($father_replies as $father_reply) {
            //0未读， 1已读，2未处理，3已读未处理，4已处理 5已完成
            if (($father_reply['is_read'] == 0) || ($father_reply['is_read'] == 1)){
                $sendFlag = $sendFlag + 1;
            }
            if (($father_reply['is_read'] == 2) || ($father_reply['is_read'] == 3)){
                $taskManage = $taskManage + 1;
                $status = 3;
            }
            if ($father_reply['is_read'] == 5){
                $taskDone = $taskDone + 1;
                $status = 3;
            }
            if ($father_reply['is_read'] == 4) {
                $status = 2;
                break;
            }
        }
        $replies_count = count($father_replies);
        if ($replies_count == $sendFlag) {
            $status = 1;
        }
        if ($replies_count == $taskManage) {
            $status = 3;
        }
        if ($replies_count == $taskDone) {
            $status = 4;
        }

        $notice['status'] = $status;
        M('OaNotice')->save($notice);
    }

    public function AddSupperviseNewRelpy () {
        if (empty(I('data'))) {
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        $data = json_decode(I('data'),true);

        $data['time'] = NOW_TIME;
        $data['is_read'] = 0;
        $res = M('OaNoticeTaskReply')->add($data);
        if ($res === false) {
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return,'数据保存失败'));
        } else{
            $father_reply = M('OaNoticeTaskReply')->where(array('id'=>$data['pid']))->find();
            if (empty($father_reply)) {
                $return['errcode'] = '61451';
                echo api_return($return['errcode'],$res,error_msg($return,'can not find father!!'));
                return;
            }
            if ($father_reply['sender'] == $this->cur_emp_id) {
                $father_reply['is_read'] = 2;
            } else {
                $father_reply['is_read'] = 4;
            }
            M('OaNoticeTaskReply')->save($father_reply);
            $this->updateNoticeState($father_reply['noticeid']);
            echo api_return(0,null);
        }
    }
    public function SetTaskDone () {
        $notice = M('OaNotice')->where(array('id'=>I('noticeId')))->find();
        $father_reply = M('OaNoticeTaskReply')->where(array('id'=>I('pid')))->find();
        $father_reply['is_read'] = 5;  // 任务完成
        M('OaNoticeTaskReply')->save($father_reply);

        $allFathers = M('OaNoticeTaskReply')->where(array('noticeid'=>I('noticeId'),'pid'=>0))->select();
        $alltaskHasDone = true;
        foreach ($allFathers as $father) {
            if ($father['is_read'] != 5) {
                $alltaskHasDone = false;
                break;
            }
        }
        if ($alltaskHasDone === true) {
            $notice['status'] = 4;
            M('OaNotice')->save($notice);
        } else {
            $notice['status'] = 3;
        }
        echo api_return(0,null);
    }
}
